package sd.qd.xiaoming.coffeedesk.support;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class FileSupport {

    @Value("${fileStoreFolderName}")
    private String fileStoreFolderName;

    public void delete(final String code) {
        File file = new File(getStoreDirectory(), code);
        System.out.println("xxxxxxxxxxxxxxxxxx");
        System.out.println(file.getAbsolutePath());
        if (file.exists()) {
            System.out.println("xxxxxxxxxxxsfdsfdsfdsfsdxxxxxxx");
            file.delete();
        }
    }

    public byte[] getBytes(final String code) {
        try {
            File store = getStoreDirectory();
            File file = new File(store, code);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            for (long i = 0; i < file.length(); i++) {
                buffer.write(fis.read());
            }
            fis.close();
            byte[] bytes = buffer.toByteArray();
            buffer.close();
            return bytes;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    public File getStoreDirectory() {
        String url = this.getClass().getClassLoader()
                .getResource("/../../" + this.fileStoreFolderName)
                .getPath();
        return new File(url);
    }

    public boolean save(final String fileName, final byte[] bytes) {
        try {
            File file = new File(getStoreDirectory(), fileName);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bytes);
            fos.close();
            return true;
        } catch (IOException e) {
            return false;
        }
    }

}
